<?php


namespace App\Utils;

use App\Models\Settings\Code;
use App\Models\Settings\CodeValue;
use Throwable;

/**
 * 迁移帮助类
 * Class MigrationUtil
 * @package App\Utils
 */
class  MigrationUtil
{


    /**
     * 添加系统代码
     * @param $code
     * @param $name
     * @param array $values
     * @throws Throwable
     */
    static function addCodes($code, $name, $values = [])
    {
        $desc = '';
        foreach ($values as $value) {
            $desc .= ($value . '、');
        }
        Code::create([
            'name' => $name,
            'code' => $code,
            'desc' => trim($desc, '、')
        ]);
        self::addCodeValue($code, $values);
    }


    /**
     * 删除编码
     * @param $code
     * @param $values
     */
    static function removeCodeValue($code, $values)
    {
        CodeValue::query()
            ->where('code', '=', $code)
            ->whereIn('value', $values)
            ->delete();
    }

    /**
     * 删除编码
     * @param $code
     */
    static function removeCode($code)
    {
        Code::query()
            ->where('deleted_at', '=', 0)
            ->where('code', '=', $code)
            ->delete();
        CodeValue::query()
            ->where('code', '=', $code)
            ->delete();
    }

    /**
     * 添加系统代码的值
     * @param $code
     * @param array $values
     * @throws Throwable
     */
    static function addCodeValue($code, $values = [])
    {
        $codeValue = [];
        foreach ($values as $key => $value) {
            $codeValue[] = [
                'value' => $key,
                'code' => $code,
                'name' => $value,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'desc' => $value
            ];
        }
        CodeValue::query()->insert($codeValue);
    }

    /**
     * @param $code
     * @param array $values
     * @throws RetailException
     */
    static function saveCodeValue($code, $values = [])
    {
        foreach ($values as $key => $value) {
            $model = CodeValue::query()
                ->where('code', '=', $code)
                ->where('value', '=', $key)
                ->where('deleted_at', '=', 0)
                ->first();
            if (!empty($model)) {
                $model['name'] = $value;
                $model['desc'] = $value;
                $model->save();
            } else {
                CodeValue::create([
                    'value' => $key,
                    'code' => $code,
                    'name' => $value,
                    'created_at' => date('Y-m-d H:i:s'),
                    'desc' => $value
                ]);
            }
        }
    }
}